<template>
  <div class="health-box" style="padding-right: 12px">
    <div class="title-box">
      <div class="title-item-left">
        <span class="text-icon" />
        健康档案
      </div>
    </div>
    <div>
      <a-tabs v-model:activeKey="activeKey" type="card" @change="changeTab">
        <a-tab-pane :key="1" tab="基本信息" style="height: calc(100vh - 320px)">
          <div class="records-content">
            <a-form
              :model="patInfoForm"
              ref="patInfoFormRef"
              :labelCol="{ style: { width: '90px' } }"
              class="patForm"
            >
              <div class="form-title">基础信息</div>
              <div style="display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 0 20px">
                <a-form-item name="patName" label="姓名">
                  <a-input v-model:value="patInfoForm.patName" disabled placeholder="请输入姓名" />
                </a-form-item>
                <a-form-item name="gender" label="性别">
                  <a-input v-model:value="patInfoForm.gender" disabled placeholder="请选择性别" />
                </a-form-item>
                <a-form-item name="age" label="年龄">
                  <a-input v-model:value="patInfoForm.age" disabled placeholder="请输入年龄" />
                </a-form-item>
                <a-form-item name="idType" label="证件类型">
                  <a-input
                    v-model:value="patInfoForm.idType"
                    disabled
                    placeholder="请选择证件类型"
                  />
                </a-form-item>
                <a-form-item name="idNo" label="证件号">
                  <a-input v-model:value="patInfoForm.idNo" disabled placeholder="请输入证件号" />
                </a-form-item>
                <a-form-item name="phone" label="联系电话">
                  <a-input v-model:value="patInfoForm.phone" disabled placeholder="请输入手机号" />
                </a-form-item>
                <a-form-item name="aboCode" label="ABO血型">
                  <a-select
                    placeholder="请选择ABO血型"
                    v-model:value="patInfoForm.aboCode"
                    :options="state.aboCode.list"
                    showSearch
                    @change="selectDataChange($event, state.aboCode.list, 'abo')"
                  />
                </a-form-item>
                <a-form-item name="rhCode" label="Rh血型">
                  <a-select
                    placeholder="请选择Rh血型"
                    v-model:value="patInfoForm.rhCode"
                    :options="state.rhCode.list"
                    showSearch
                    @change="selectDataChange($event, state.rhCode.list, 'rh')"
                  />
                </a-form-item>
                <a-form-item name="height" label="身高">
                  <a-input-number
                    :min="0"
                    :max="250"
                    :precision="1"
                    v-model:value="patInfoForm.height"
                    placeholder="请输入身高"
                  />
                </a-form-item>
                <a-form-item name="weight" label="体重">
                  <a-input-number
                    :min="0"
                    :max="200"
                    :precision="1"
                    v-model:value="patInfoForm.weight"
                    placeholder="请输入体重"
                  />
                </a-form-item>
                <a-form-item name="waist" label="腰围">
                  <a-input-number
                    :min="0"
                    :max="200"
                    :precision="1"
                    v-model:value="patInfoForm.waist"
                    placeholder="请输入腰围"
                  />
                </a-form-item>
                <a-form-item name="hip" label="臀围">
                  <a-input-number
                    :min="0"
                    :max="200"
                    :precision="1"
                    v-model:value="patInfoForm.hip"
                    placeholder="请输入臀围"
                  />
                </a-form-item>

                <a-form-item name="nationCode" label="民族">
                  <a-select
                    placeholder="请选择民族"
                    v-model:value="patInfoForm.nationCode"
                    :options="state.nationCode.list"
                    showSearch
                    @change="selectDataChange($event, state.nationCode.list, 'nation')"
                  />
                </a-form-item>
                <a-form-item name="maritalCode" label="婚姻状况">
                  <a-select
                    placeholder="请选择婚姻状况"
                    v-model:value="patInfoForm.maritalCode"
                    :options="state.maritalCode.list"
                    showSearch
                    @change="selectDataChange($event, state.maritalCode.list, 'marital')"
                  />
                </a-form-item>
                <a-form-item name="educationCode" label="学历">
                  <a-select
                    placeholder="请选择学历"
                    v-model:value="patInfoForm.educationCode"
                    :options="state.educationCode.list"
                    showSearch
                    @change="selectDataChange($event, state.educationCode.list, 'education')"
                  />
                </a-form-item>
                <a-form-item name="medicareCode" label="支付方式">
                  <a-select
                    placeholder="请选择支付方式"
                    v-model:value="patInfoForm.medicareCode"
                    :options="state.medicareCode.list"
                    showSearch
                    @change="selectDataChange($event, state.medicareCode.list, 'medicare')"
                  />
                </a-form-item>
                <a-form-item name="occupationCode" label="职业类别">
                  <a-select
                    placeholder="请选择职业类别"
                    v-model:value="patInfoForm.occupationCode"
                    :options="state.occupationCode.list"
                    showSearch
                    @change="selectDataChange($event, state.occupationCode.list, 'occupation')"
                  />
                </a-form-item>
              </div>
              <div class="form-title">现住址</div>
              <div
                style="display: grid; grid-template-columns: repeat(1, 1fr 2fr); grid-gap: 0 10px"
              >
                <a-form-item name="areaValue" label="地址">
                  <a-cascader
                    v-model:value="areaValue"
                    :options="optionsArea"
                    :load-data="loadAreaData"
                    placeholder="请选择"
                    change-on-select
                  />
                </a-form-item>
                <a-form-item name="address" label="详细地址">
                  <a-input
                    v-model:value="patInfoForm.address"
                    placeholder="请输入详细地址"
                    :title="patInfoForm.address"
                    autocomplete="off"
                  />
                </a-form-item>
              </div>
              <div class="form-title">联系人</div>
              <div style="display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 0 20px">
                <a-form-item name="contactRelationCode" label="关系">
                  <a-select
                    placeholder="请选择关系"
                    v-model:value="patInfoForm.contactRelationCode"
                    :options="state.contactRelationCode.list"
                    showSearch
                    @change="
                      selectDataChange($event, state.contactRelationCode.list, 'contactRelation')
                    "
                  />
                </a-form-item>
                <a-form-item name="contactName" label="姓名">
                  <a-input v-model:value="patInfoForm.contactName" placeholder="请输入姓名" />
                </a-form-item>
                <a-form-item
                  name="contactPhone"
                  label="电话"
                  :rules="[{ trigger: 'change', validator: phoneValidator }]"
                >
                  <a-input v-model:value="patInfoForm.contactPhone" placeholder="请输入电话" />
                </a-form-item>
              </div>
            </a-form>
          </div>
          <div class="records-footer">
            <a-button type="primary" @click="savePatInfo">保存</a-button>
          </div>
        </a-tab-pane>
        <a-tab-pane :key="2" tab="医疗信息" style="height: calc(100vh - 320px)">
          <div class="medical-content">
            <div class="form-title">疾病史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.elapseHis">
                <div class="tag-item">
                  {{ medicalInfoList.elapseHis }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>
            <div class="form-title">过敏史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.allergyHis">
                <div class="tag-item">
                  {{ medicalInfoList.allergyHis }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>
            <div class="form-title">家族史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.familyHis">
                <div class="tag-item">
                  {{ medicalInfoList.familyHis }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>
            <div class="form-title">外伤史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.hurtHis">
                <div class="tag-item">
                  {{ medicalInfoList.hurtHis }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>
            <div class="form-title">手术史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.oprtHst">
                <div class="tag-item">
                  {{ medicalInfoList.oprtHst }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>
            <div class="form-title">预防接种史</div>
            <div class="tag-content">
              <template v-if="medicalInfoList.pvtIncltHst">
                <div class="tag-item">
                  {{ medicalInfoList.pvtIncltHst }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </div>

            <template v-if="patInfoForm.gender == '女性'">
              <div class="form-title">月经史</div>
              <div class="tag-content">
                <template v-if="medicalInfoList.mouthHis">
                  <div class="tag-item">
                    {{ medicalInfoList.mouthHis }}
                  </div>
                </template>
                <template v-else>
                  <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
                </template>
              </div>
              <div class="form-title">婚育史</div>
              <template v-if="medicalInfoList.marriageHis">
                <div class="tag-item">
                  {{ medicalInfoList.marriageHis }}
                </div>
              </template>
              <template v-else>
                <div style="font-size: 14px; font-weight: 400; color: #4e5969">暂无数据</div>
              </template>
            </template>
          </div>
          <!-- medicalInfoList -->
        </a-tab-pane>
        <a-tab-pane :key="3" tab="生活习惯" style="height: calc(100vh - 320px)">
          <div class="records-content">
            <template v-if="livingHabitForm.length">
              <LivingForm v-model:form-data="livingHabitForm" style="margin-right: 10px" />
            </template>
            <template v-else>
              <a-empty style="padding-top: 30px" />
            </template>
          </div>
          <div class="records-footer" v-if="livingHabitForm.length > 0">
            <a-button type="primary" @click="saveFormData">保存</a-button>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  getDictAreaList,
  getPatientInfo,
  getDictList,
  updatePatientInfo,
  getMedicalInfo,
  getQuestionnaireAnswer,
  saveQuestionnaireNew,
  getQuestionnaireInfo
} from './healthRecords.api'
import LivingForm from '@/components/LivingForm/index.vue'
import { message } from 'ant-design-vue'

const activeKey = ref<number>(1)
const patEmpi = ref<string>('')
const areaValue = ref<any>([])
const optionsArea = ref([])

const livingHabitForm = ref<any>([])

interface State {
  [key: string]: { list: any[]; label: string; code: string }
}

interface formObj {
  [key: string]: any
}

const state = reactive<State>({
  aboCode: {
    list: [],
    label: 'aboCode', // ABO血型
    code: 'CV04.50.005'
  },
  rhCode: {
    list: [],
    label: 'rhCode', // Rh血型
    code: 'CV04.50.020'
  },
  medicareCode: {
    list: [],
    label: 'medicareCode', // 医疗支付方式
    code: 'CV07.10.005'
  },
  maritalCode: {
    list: [],
    label: 'maritalCode', // 婚姻状况
    code: 'GB/T_2261.2-2003'
  },
  nationCode: {
    list: [],
    label: 'nationCode', // 民族
    code: 'GB_3304-1991'
  },
  educationCode: {
    list: [],
    label: 'educationCode', // 文化程度
    code: 'GB/T_4658-1984'
  },
  occupationCode: {
    list: [],
    label: 'occupationCode', // 职业类别
    code: 'GB/T_6565-2009'
  },
  contactRelationCode: {
    list: [],
    label: 'contactRelationCode', // 联系人关系
    code: 'GB/T_4761-2008'
  }
  // {
  //   list: [],
  //   label: 'nationalityCode', // 国籍
  //   code: 'GB/T_4761-2008'
  // }
})

const stateForm = reactive<any>({
  questionListOld: [],
  questionInfo: [],
  questionList: []
})

const phoneValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.resolve()
  }
  if (!/^1[3-9]\d{9}$/.test(value) && !/^(0\d{2,3}-?\d{7,8})$/.test(value)) {
    return Promise.reject('请输入正确的电话')
  } else {
    return Promise.resolve()
  }
}

const patInfoForm = reactive<formObj>({
  patName: '',
  gender: '',
  age: '',
  idType: '',
  idNo: '',
  phone: '',
  aboCode: '',
  rhCode: '',
  height: '',
  weight: '',
  waist: '',
  hip: '',
  nationCode: '',
  maritalCode: '',
  educationCode: '',
  medicareCode: '',
  occupationCode: '',
  contactRelationCode: '',
  contactName: '',
  contactPhone: ''
})
const patInfoFormRef = ref()

const init = (empi: string) => {
  patEmpi.value = empi
  nextTick(async () => {
    if (patInfoFormRef.value) {
      patInfoFormRef.value.resetFields()
    }
    activeKey.value = 1
    await getProvince()
    await initializeCascader()
    await getInfo()
    const keys = Object.keys(state)
    keys.forEach(async (vo: string) => {
      await getDictData(state[vo], state[vo].code)
    })
  })
}

// 根据类型获取字典数据
const getDictData = async (
  data: { list: any[]; label: string; code: string },
  typeCode: string
) => {
  await getDictList({ type: typeCode, label: '' }).then(async (res: any) => {
    data.list = res.data.list.map((vo: any) => {
      return {
        value: vo.dictValue,
        label: vo.dictLabel
      }
    })
  })
}

// tab切换
const changeTab = async (e: any) => {
  activeKey.value = e
  const keys = Object.keys(state)
  switch (e) {
    case 1:
      await getProvince()
      await getInfo()
      keys.forEach(async (vo: string) => {
        await getDictData(state[vo], state[vo].code)
      })
      break
    case 2:
      getMedicalInfoData()
      break
    case 3:
      getQuestionnaireData()
      break
    default:
      break
  }
}

// 基本信息
const weight = ref<any>()
const height = ref<any>()
const waist = ref<any>()
const hip = ref<any>()
const getInfo = async () => {
  getPatientInfo({ empi: patEmpi.value }).then(async (res: any) => {
    Object.assign(patInfoForm, res.data)
    weight.value = patInfoForm.weight
    height.value = patInfoForm.height
    waist.value = patInfoForm.waist
    hip.value = patInfoForm.hip

    if (res.data) {
      // 填充 areaValue
      areaValue.value = [
        res.data.addressProvinceCode || null,
        res.data.addressCityCode || null,
        res.data.addressCountryCode || null
      ].filter((item) => item)

      await initializeCascader()
    } else {
      areaValue.value = []
    }
  })
}

const initializeCascader = async () => {
  // 确保路径上的所有节点都加载完毕
  const valuePath = [...areaValue.value]
  let options = optionsArea.value

  for (let i = 0; i < valuePath.length; i++) {
    const value = valuePath[i]
    const currentOption: any = options.find((opt) => opt.value === value)

    if (!currentOption) {
      break
    }

    // 动态加载子节点
    if (!currentOption.children && i < valuePath.length - 1) {
      await loadAreaData([currentOption])
    }

    options = currentOption.children || []
  }
}

// 医疗信息
const medicalInfoList = ref({})
const getMedicalInfoData = () => {
  getMedicalInfo({ empi: patEmpi.value }).then((res: any) => {
    console.log(res.data)
    medicalInfoList.value = res.data
  })
}

// 生活习惯
const livingHabitData = ref<any>()
const getQuestionnaireData = async () => {
  getQuestionnaireInfo({ questionnaireKey: 'habits_customs_questionnaire' }).then(async (res) => {
    livingHabitData.value = res.data
    const details = res.data.content
    await getQuestionnaireAnswer({ empi: patEmpi.value }).then((res: any) => {
      if (res.data) {
        const answers = res.data
        const questionList = JSON.parse(details)

        const convertList = convert(questionList)

        convertList.forEach((v) => {
          v.list.forEach((u) => {
            const item = answers.filter((w) => {
              return w.relationQuestionCode === u.relationQuestionCode
            })
            if (u.type.includes('多选')) {
              const checkData: any = []
              item.forEach((w) => {
                checkData.push(w.content)
              })

              u.value = checkData
              u.sort = u.options
                .filter((vo) => {
                  return checkData.join(',').includes(vo.value)
                })
                .map((op) => {
                  return op.sort
                })
                .join(',')
              u.inputText = u.value
            } else {
              if (item && item.length) {
                u.value = item[0].content
                const findOption = u.options.find((vo) => vo.value == item[0].content)
                u.sort = findOption ? findOption.sort : ''
                u.inputText = item[0].content
              }
            }
            u.questionnaireRecordId = item[0].questionnaireRecordId
          })
        })

        stateForm.questionListOld = convertList
        stateForm.questionInfo = res.data

        stateForm.questionList = showCondition(stateForm.questionListOld)

        livingHabitForm.value = stateForm.questionList
        // console.log(livingHabitForm.value, answers)
      } else {
        livingHabitForm.value = []
        // message.warning('该患者未注册！')
      }
    })
  })
}

const getProvince = () => {
  getDictAreaList({ patientId: 0 }).then((res: any) => {
    optionsArea.value = res.data.map((vo: any) => {
      return {
        value: vo.dictValue,
        label: vo.dictLabel,
        isLeaf: false,
        index: 0
      }
    })
  })
}

const loadAreaData = async (selectedOptions: any) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  // console.log(targetOption)
  if (targetOption.index == 0) {
    patInfoForm.addressProvinceCode = targetOption.value
    patInfoForm.addressProvince = targetOption.label
  } else if (targetOption.index == 1) {
    patInfoForm.addressCityCode = targetOption.value
    patInfoForm.addressCity = targetOption.label
  } else {
    patInfoForm.addressCountryCode = targetOption.value
    patInfoForm.addressCountry = targetOption.label
  }
  targetOption.loading = true
  try {
    const response = await getDictAreaList({ patientId: targetOption.value })
    const children = response.data.map((vo) => ({
      value: vo.dictValue,
      label: vo.dictLabel,
      isLeaf: targetOption.index + 1 === 2 ? true : false, // 第三层设置为叶子节点
      index: targetOption.index + 1 // 更新 index
    }))

    targetOption.loading = false
    targetOption.children = children
    optionsArea.value = [...optionsArea.value] // 浅拷贝触发视图更新
  } catch (error) {
    targetOption.loading = false
  }
}

// 选项切换
const selectDataChange = (e: any, data: any, label: string) => {
  const filterData = data.filter((item: any) => item.value == e)
  patInfoForm[label] = filterData && filterData.length ? filterData[0].label : ''
}

// 更新患者信息
const savePatInfo = () => {
  if (areaValue.value && areaValue.value.length > 0) {
    if (areaValue.value[0]) {
      patInfoForm.addressProvince = optionsArea.value.filter(
        (vo) => vo.value == areaValue.value[0]
      )[0].label
      patInfoForm.addressProvinceCode = optionsArea.value.filter(
        (vo) => vo.value == areaValue.value[0]
      )[0].value
    }

    if (areaValue.value[1]) {
      const cityList = optionsArea.value.filter((vo) => vo.value == areaValue.value[0])[0].children
      patInfoForm.addressCity = cityList.filter((vo) => vo.value == areaValue.value[1])[0].label
      patInfoForm.addressCityCode = cityList.filter((vo) => vo.value == areaValue.value[1])[0].value
    }

    if (areaValue.value[2]) {
      const cityList = optionsArea.value.filter((vo) => vo.value == areaValue.value[0])[0].children
      const countryList = cityList.filter((vo) => vo.value == areaValue.value[1])[0].children
      patInfoForm.addressCountry = countryList.filter(
        (vo) => vo.value == areaValue.value[2]
      )[0].label
      patInfoForm.addressCountryCode = countryList.filter(
        (vo) => vo.value == areaValue.value[2]
      )[0].value
    }
  } else {
    patInfoForm.addressCity = null
    patInfoForm.addressCityCode = null
    patInfoForm.addressCountry = null
    patInfoForm.addressCountryCode = null
    patInfoForm.addressProvince = null
    patInfoForm.addressProvinceCode = null
  }
  // console.log(state)
  // console.log(patInfoForm)

  const data = JSON.parse(JSON.stringify(patInfoForm))
  delete data.patName
  delete data.idNo
  delete data.phone

  if (weight.value == data.weight && height.value == data.height) {
    data.weight = null
    data.height = null
  }

  if (waist.value == data.waist && hip.value == data.hip) {
    data.waist = null
    data.hip = null
  }

  updatePatientInfo(data).then(() => {
    message.success('保存成功')
  })

  // const keys = Object.keys(state)
  // keys.forEach((vo: string) => {
  //   console.log(patInfoForm[vo])
  // })
}

// 更新生活习惯
const saveFormData = () => {
  const params: any = {
    questionnaireKey: 'habits_customs_questionnaire',
    patientQuestionnaireAnswerVOs: [],
    questionnaireRecordId: undefined
  }
  livingHabitForm.value.forEach((vo) => {
    vo.list.forEach((val: any) => {
      const answerModel = {
        userId: '',
        empi: patEmpi.value,
        questionId: val.id,
        questionnaireId: livingHabitData.value.questionnaireId,
        relationQuestionCode: val.relationQuestionCode,
        questionnaireRecordId: val.questionnaireRecordId,
        optionId: '',
        content: '',
        extContent: val.type == '选择 + 输入' ? val.inputText : '',
        score: val.score || 0
      }
      if (val.type == '单选' || val.type == '输入') {
        const answer = {
          ...answerModel,
          optionId: val.type == '单选' && val.optionId ? String(val.optionId) : '',
          content: val.value
        }
        if (!val.show) {
          answer.content = val.options[0].value
          answer.optionId = val.options[0].id + ''
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      } else if (val.type == '多选') {
        if (val.value && val.value.length > 0) {
          val.optionId = val.options
            .filter((item) => val.sort.includes(item.sort))
            .map((item) => item.id)
          val.score = val.options
            .filter((item) => val.sort.includes(item.sort))
            .map((item) => item.score)
          val.value.forEach((i: string, idx: number) => {
            const answer = {
              ...answerModel,
              optionId: val.optionId[idx] + '',
              content: i,
              score: val.score[idx]
            }
            params.patientQuestionnaireAnswerVOs.push(answer)
          })
        } else {
          const answer = {
            ...answerModel,
            optionId: '',
            content: '',
            score: ''
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        }
      } else {
        const answer = {
          ...answerModel,
          optionId: val.type == '单选' && val.optionId ? String(val.optionId) : '',
          content: val.type == '输入' ? val.inputText : val.value
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      }
    })
  })

  params.questionnaireRecordId = params.patientQuestionnaireAnswerVOs[0]
    ? params.patientQuestionnaireAnswerVOs[0].questionnaireRecordId
    : undefined

  saveQuestionnaireNew(params).then(() => {
    message.success('保存成功')
  })
}

const convert = (content) => {
  return content.map((v) => {
    v.list = v.list.map((w) => {
      if (w.options && w.options.length) {
        w.options.map((u) => {
          u['scale'] = false
        })
      }
      return {
        id: w.id,
        name: w.questionName,
        type: w.questionType,
        sort: w.sort,
        inputText: w.inputText,
        inputMode: w.inputMode,
        rules: w.rules,
        config: w.config,
        options: w.options,
        value: w.value,
        showCondition: w.showCondition || null,
        exc: w.exc ? JSON.parse(w.exc) : '',
        relationQuestionCode: w.relationQuestionCode,
        questionSource: w.questionSource,
        relationQuestionId: w.relationQuestionId,
        show: true
      }
    })
    return v
  })
}

const showCondition = (arr) => {
  const obj = {}
  arr.map((v) => {
    v.list.map((u) => {
      obj[u.id] = u
    })
  })

  const List = []

  for (const v of arr) {
    const L = v.list.filter((u) => {
      if (!u.showCondition) {
        return true
      }
      let show = true
      if (Object.prototype.hasOwnProperty.call(u.showCondition, 'show')) {
        show = u.showCondition.show
      }
      let r
      try {
        r = loop(u.showCondition, obj)
      } catch (e) {
        throw new Error(`自定义条件执行异常，异常问题：${u.name}`)
      }

      u.show = r
      // if (show) {
      //   return r
      // } else {
      //   return !r
      // }
      return true
    })
    if (L.length) {
      List.push({
        ...v,
        list: L
      })
    }
  }
  return List
}

const loop = (obj, d) => {
  if (obj.operator === 'AND') {
    return obj.conditions.every((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (v.id === 'custom') {
            return transformCustom(v.value, d)
          } else if (d[v.id].type.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].type.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].type === '数字选择') {
            const f = transform(v)
            return f(d[v.id].value)
          } else if (d[v.id].type === '输入') {
            const f = transform(v)
            return f(d[v.id].value)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  } else if (obj.operator === 'OR') {
    return obj.conditions.some((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (v.id === 'custom') {
            return transformCustom(v.value, d)
          } else if (d[v.id].type.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].type.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].type === '数字选择') {
            const f = transform(v)
            return f(d[v.id].value)
          } else if (d[v.id].type === '输入') {
            const f = transform(v)
            return f(d[v.id].value)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  }
  return true
}

const transform = (obj) => {
  if (typeOf(obj.value) === 'string') {
    return new Function('x', 'return x ' + obj.operator + ' "' + obj.value + '"')
  } else {
    return new Function('x', 'return x ' + obj.operator + ' ' + obj.value)
  }
}

const transformCustom = (str, obj) => {
  const s = str.replace(/\$\{(.*?)\}/g, (_, key) => {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return obj[key].value
    } else {
      throw new Error('自定义条件执行异常找不到变量')
    }
  })
  const f = new Function('x', 'return ' + s)
  console.log(f())
  return f()
}

defineExpose({
  init
})
</script>

<style lang="less" scoped>
.title-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  margin: 0 0 10px;
  font-weight: 600;
  line-height: 32px;
  color: #1d2129;

  .title-item-left {
    font-size: 18px;
    font-weight: 600;
  }

  .text-icon {
    display: inline-block;
    width: 3px;
    height: 16px;
    margin-right: 8px;
    line-height: 32px;
    background: #165dff;
  }
}

.records-content {
  height: calc(100% - 56px);
  margin-bottom: 12px;
  overflow: hidden auto;
}

.medical-content {
  height: calc(100% - 10px);
  overflow: hidden auto;
}

.records-footer {
  padding: 12px 0;
  text-align: left;
  border-top: 1px solid #e5e6eb;
}

.form-title {
  padding: 8px 16px;
  margin-bottom: 10px;
  font-weight: 600;
  background: #f7f8fa;
}

.patForm {
  margin-right: 10px;

  .ant-form-item {
    .ant-input-number,
    .ant-input {
      width: 100%;
    }

    .ant-select.ant-select-in-form-item {
      width: 100%;
    }
  }
}

.tag-content {
  display: flex;
  margin-bottom: 24px;

  .tag-item {
    padding: 6px 8px;
    margin-top: 2px;
    margin-right: 16px;
    font-size: 14px;
    font-weight: 500;
    color: #165dff;
    background: #e8f3ff;
    border: 1px solid #165dff;
    border-radius: 2px;
  }
}
</style>
